# -*- coding: utf-8 -*-
from tg import config
import os,shutil
from hashlib import md5
uploads = config.get('uploads')

def md5_for_file(f, block_size=2**20):
    """
    read file in chunks as some files may be quite large - stuff
    like pdf contracts > 100 pages, all scanned thus using images
    found at http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python
    """
    mymd5 = md5()
    f_o = open(f,"r")
    while True:
        data = f_o.read(block_size)
        if not data:
            break
        mymd5.update(data)
    f_o.close()
    return mymd5.hexdigest()


def uploadFile(fileobj):
    """ Save an uploaded file from the tempfile locations used by request.POST to
        a permanent home in uploads."""
    target = os.path.join(uploads,fileobj.filename.lstrip(os.sep))
    orig_file_name = fileobj.filename # this is what the end user expects to see
    file_name,base_file_name,return_name = fileobj.filename,fileobj.filename,fileobj.filename
    if os.path.isfile(target): # filename already exists? This is distinctly possible
        have_valid,iter = False,0
        while not have_valid: # allow for 9999 variations of filename - bit over the top
            base_file_name = "000%s_"%str(iter)
            return_name = "%s%s"%(base_file_name,fileobj.filename)
            file_name = "%s%s%s"%(uploads,base_file_name,fileobj.filename)
            if not os.path.isfile(file_name):
                target = file_name
                have_valid = True
            else:
                iter+=1
    try:
        permanent_file = open(target,'w')
        shutil.copyfileobj(fileobj.file, permanent_file)
        fileobj.file.close()
        permanent_file.close()
    except Exception,e:
        raise
    else:
        file_md5 = md5_for_file(target)
        file_size = os.path.getsize(target)
        return dict(file_md5=file_md5,file_size=file_size,file_name=return_name,orig_file_name=orig_file_name)

